#include "common/http/HttpResponse.h"
#include "common/comm/AgentManager.h"
#include "common/http/HttpAgent.h"

#include <iostream>
using namespace std;

HttpResponse::HttpResponse()
    : line_("")
    , isReadAll_(false)
    , readIndex_(0)
    , alreadyRead_(0)
    , contentLength_(0)
{}

HttpResponse::~HttpResponse() {}

bool HttpResponse::parseResponseData(std::string unParseData)
{
    size_t pos1 = 0;
    size_t pos2 = 0;
    string tmp = "";
    pos2 = unParseData.find("\r\n");
    line_ = unParseData.substr(pos1, pos2 - pos1);
    while (1) {
        pos1 = pos2 + 2;
        pos2 = unParseData.find("\r\n", pos1);
        if (pos1 == pos2) break;
        tmp = unParseData.substr(pos1, pos2 - pos1);
        parseHeader(tmp);
    }

    body_ = unParseData.substr(pos1 + 2, unParseData.length() - 1);

    auto it = headers_.find("Content-Length");
    if (it != headers_.end()) {
        contentLength_ = atoi(it->second.c_str());
        if (body_.length() == contentLength_) {
            isReadAll_ = true;
        } else if (body_.length() < contentLength_) {
            readIndex_ = contentLength_ - body_.length();
            alreadyRead_ = body_.length();
        }
    }
    return true;
}

bool HttpResponse::appendBody(std::string residueBuffer)
{
    body_.append(residueBuffer);
    // 检查body长度和contentLength_是否一样
    if (body_.length() == contentLength_) {
        return true;
    } else {
        return false;
    }
}

// --------- private ------------
void HttpResponse::parseHeader(std::string &header)
{
    size_t pos = 0;
    pos = header.find(": ");
    headers_.insert(std::make_pair(
        header.substr(0, pos), header.substr(pos + 2, header.length() - 1)));
}